<template>
    <div class="permission-container">
        <div class="boxWrapper tabbox">
            <el-tabs v-model="currentName">
                <el-tab-pane label="组织架构" name="1">
                    <span slot="label"><i class="iconfont">&#xe687;</i> 组织架构</span>
                </el-tab-pane>
                <el-tab-pane label="角色管理" name="2">
                    <span slot="label"><i class="iconfont">&#xe6f4;</i> 角色管理</span>
                </el-tab-pane>
                <el-tab-pane label="权限设置" name="3">
                    <span slot="label"><i class="iconfont">&#xe62a;</i> 用户权限</span>
                </el-tab-pane>
                <el-tab-pane label="用户设置" name="4">
                    <span slot="label"><i class="iconfont">&#xe624;</i> 用户设置</span>
                </el-tab-pane>
            </el-tabs>
        </div>

        <!-- 组织架构内容 -->
        <div class="content" v-show="currentName == 1">
            <cardBox class="left-wrapper" title="目录" icon="&#xe6f2;">
                <treeMenu 
                    :treeData="companyTreeMenu" 
                    name="orgname"  
                    @menuLeftClick="handleMenuClick" 
                    nodeKey="orgid" 
                    expandALL 
                    ref="treeMenu" 
                    isCompany 
                    isRightMenu 
                    @addMenuItem="handleAddMenu" 
                    @delMenuItem="handleDelTreeMenu" 
                    @editMenuItem="handleAddMenu"
                    :showRoleAdd="permissions.showRoleAdd"
                    :showRoleEdit="permissions.showRoleEdit"
                    :showRoleDel="permissions.showRoleDel"
                />
            </cardBox>

            <!-- 右侧电站管理 -->
            <div class="right-wrapper boxWrapper">
                <div class="station-header">
                    <div class="header-left">
                        <el-select v-model="basinId" placeholder="选择流域" @change="handleChangeBasin" clearable size="small">
                            <el-option
                                v-for="item in basinList"
                                :key="item.id"
                                :label="item.basinName"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </div>
                    <el-button 
                        type="primary" 
                        size="small" 
                        @click="handleSaveOrgStation" 
                        icon="el-icon-circle-check"
                        :loading="saving"
                        v-if="permissions.showRoleEdit"
                    >
                        保存设置
                    </el-button>
                </div>

                <!-- 电站卡片列表 -->
                <div class="station-content">
                    <div class="station-cards">
                        <div 
                            v-for="station in filteredStationList" 
                            :key="station.id"
                            class="station-card"
                            :class="{ 'selected': isStationSelected(station) }"
                        >
                            <div class="card-main" @click="handleCardClick(station)">
                                <div class="card-header">
                                    <div class="station-name">
                                        <i class="el-icon-office-building"></i>
                                        {{ station.stationName }}
                                    </div>
                                </div>
                                
                                <div class="card-content">
                                    <div class="info-item">
                                        <span class="label">位置：</span>
                                        <span class="value">{{ station.location || '--' }}</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="label">坝高：</span>
                                        <span class="value">{{ station.damHeight || '--' }} m</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="label">大坝类型：</span>
                                        <span class="value">{{ station.damCategory || '--' }}</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="label">库容：</span>
                                        <span class="value">{{ station.reservoirCapacity || '--' }}</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="label">装机容量：</span>
                                        <span class="value">{{ station.installation || '--' }}</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="label">工程等级：</span>
                                        <span class="value">{{ station.scale || '--' }}</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="label">投产时间：</span>
                                        <span class="value">{{ station.productionTime || '--' }}</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 选择控制区域 - 独立出来避免事件冲突 -->
                            <div class="card-controls">
                                <el-checkbox 
                                    :value="isStationSelected(station)" 
                                    @change="(val) => handleCheckboxChange(station, val)"
                                    class="station-checkbox"
                                >
                                    <span class="checkbox-label">选择</span>
                                </el-checkbox>
                                
                                <div class="selected-badge" v-if="isStationSelected(station)">
                                    <i class="el-icon-check selected-icon"></i>
                                    <span class="selected-text">已选择</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 选择统计 -->
                <div class="selection-info" v-if="selectTableStation.length > 0">
                    <el-tag type="success">
                        已选择 {{ selectTableStation.length }} 个电站
                    </el-tag>
                    <el-button 
                        type="text" 
                        @click="clearSelection"
                        style="margin-left: 10px;"
                    >
                        清空选择
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 其他页面组件 -->
        <roleList v-if="currentName == '2'" :showRoleAdd="permissions.showRoleAdd" :showRoleEdit="permissions.showRoleEdit" :showRoleDel="permissions.showRoleDel"/>

        <permissionPage v-if="currentName == '3'" :showRoleEdit="permissions.showRoleEdit"/>

        <users v-if="currentName == '4'" :showRoleAdd="permissions.showRoleAdd" :showRoleEdit="permissions.showRoleEdit" :showRoleDel="permissions.showRoleDel"/>

        <!-- 公司管理对话框 -->
        <el-dialog
            title="公司管理"  
            v-dialogDrag 
            :visible.sync="companyMenuDialog" 
            width="400px" 
            :before-close="handleCloseCompanyDialog"
        >
            <el-form ref="companyForm" :model="companyForm" label-width="80px" size="medium">
                <el-form-item label="名称">
                    <el-input v-model="companyForm.orgname" placeholder="请输入名称"></el-input>
                </el-form-item>
                <el-form-item label="类型">
                    <el-radio-group v-model="companyForm.isenterprise">
                        <el-radio :label="1">公司</el-radio>
                        <el-radio :label="0">部门</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>  
            <div class="btnGroup">
                <el-button size="small" @click="handleCloseCompanyDialog" icon="el-icon-circle-close">取消</el-button>
                <el-button type="primary" size="small" @click="handleSaveCompany" icon="el-icon-circle-check">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import treeMenu from '@/components/base/treeMenu.vue'
import cardBox from "../../components/base/cardBox.vue";
import bus from '@/utils/eventBus.js';
import roleList from '@/components/page/setting/roleList.vue'
import permissionPage from '@/components/page/setting/permissionPage.vue'
import users from '@/components/page/setting/users.vue'
import {getORGByUser,orgAdd,orgEdit,orgDel,getOrgStationByBasin,setOrgStation,GetAllByORG} from '@/api/https'
import permissionMixin from '@/utils/permission.js'
export default {
    name:'permission',
    mixins: [permissionMixin],
    components:{cardBox,treeMenu,roleList,permissionPage,users},
    data() {
        return {
            currentName:'1',
            companyTreeMenu:[],
            companyMenuDialog:false,
            companyForm:{},
            userOrgId:'',
            stationList:[],
            filteredStationList:[],
            selectTableStation:[],
            enterpriseId:'',
            isenterprise:'',
            basinId:'',
            basinList:[],
            loading: false,
            saving: false,
            treeDataEdit: false,
            treeNodeLevel: ''
        }  
    },
    mounted(){
        bus.$emit('showBasin', false);
        this.getCompanyList()
    },
    computed: {
        permissions() {
            return this.getPermissions() || {}
        }
    },
    activated(){
        bus.$emit('showBasin', false);
    },
    methods:{
        handleGetStationSelect(){
            GetAllByORG({
                ORGID:this.userOrgId
            }).then(res=>{
                if(res.isSuccess){
                    this.basinList = res.data  
                    const filterIndex = res.data.findIndex(item => item.eixsts == 1)
                    if(filterIndex > -1){
                        this.basinId = res.data[filterIndex].id
                    }else{
                        this.basinId = res.data[0].id
                    }
                    this.getStationList()
                }else{
                    this.basinList = []
                }
            })
        },
        getStationList(){
            this.loading = true
            this.selectTableStation = []
            this.stationList = []
            this.filteredStationList = []
            
            getOrgStationByBasin({
                BasinID:this.basinId,
                ORGID:this.userOrgId
            }).then(res=>{
                this.loading = false
                if(res.isSuccess){
                    this.stationList = res.data
                    this.filteredStationList = res.data
                    // 设置已选择的电站
                    res.data.forEach(item=>{
                        if(item.thisOrg == 1){
                            this.selectTableStation.push(item.id)
                        }
                    })
                }else{
                    this.selectTableStation = []
                }
            }).catch(() => {
                this.loading = false
            })
        },
        getCompanyList(){
            getORGByUser().then(res=>{
                if(res.isSuccess){
                    this.companyTreeMenu = res.data || []
                    if(res.data && res.data.length > 0){
                        this.$nextTick(()=>{
                            this.handleGetStationSelect()
                            if(this.$refs.treeMenu && this.$refs.treeMenu.$refs.tree) {
                                this.$refs.treeMenu.$refs.tree.setCurrentKey(res.data[0].orgid);
                            }
                            this.userOrgId = res.data[0].orgid
                            this.enterpriseId = res.data[0].enterpriseId
                            this.isenterprise = res.data[0].isenterprise
                            this.getStationList()
                        })
                    }
                }else{
                    this.companyTreeMenu = []
                }
            })
        },
        handleMenuClick(data){ 
            this.userOrgId = data.orgid
            this.enterpriseId = data.enterpriseId
            this.isenterprise = data.isenterprise
            this.getStationList()
            this.handleGetStationSelect()
        },
        handleCloseCompanyDialog(){
            this.companyMenuDialog = false
            this.companyForm = {}
        },
        handleAddMenu(data,isEdit,treeNodeLevel){
            this.treeDataEdit = isEdit
            this.treeNodeLevel = treeNodeLevel || ''
            if(isEdit){
                const _editData = Object.assign({},data)
                this.companyForm = {..._editData}
            }else{
                this.companyForm = {
                    id: 0,
                    orgid:0,
                    uporgid: treeNodeLevel == 1 ? data.uporgid || 0 : data.orgid || 0,
                    orgname:'',
                    isenterprise: 1,
                    enterpriseid:0
                }
            }
            this.companyMenuDialog = true
        },
        handleSaveCompany(){
            if(this.companyForm.orgname === ''){
                this.$message.error('请输入名称后在保存！')
                return false
            }
            if(this.companyForm.isenterprise === ''){
                this.$message.error('请选择类型后在保存！')
                return false
            }

            if(this.treeDataEdit){
                orgEdit(this.companyForm).then(res=>{  
                    if(res.isSuccess){
                        this.handleCloseCompanyDialog()
                        this.getCompanyList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }else{
                orgAdd(this.companyForm).then(res=>{  
                    if(res.isSuccess){
                        this.handleCloseCompanyDialog()
                        this.getCompanyList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }
        },
        handleDelTreeMenu(data){
            this.$confirm(`确认删除名称为 ${data.orgname} 的公司/部门？`,{
                type:'warning'
            }).then(() => {
                orgDel({id:data.id}).then(res=>{  
                    if(res.isSuccess){
                        this.getCompanyList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {});  
        },
        handleSaveOrgStation(){
            this.saving = true
            setOrgStation({
                enterpriseid:this.enterpriseId,
                basinID:Number(sessionStorage.getItem('basinId')),
                stationID:this.selectTableStation,
                orgid:this.userOrgId,
                isenterprise:this.isenterprise
            }).then(res=>{
                this.saving = false
                if(res.isSuccess){
                    this.$message.success('保存成功！')
                    this.getStationList()
                }else{
                    this.$message.error(res.errorMessage)
                }
            }).catch(() => {
                this.saving = false
            })
        },
        handleChangeBasin(val){
            if(this.userOrgId == ''){
                this.$message.error('请在左侧选择要查看的公司或组织')
                return false
            }
            this.basinId = val
            this.getStationList()
        },
        // 卡片点击事件
        handleCardClick(station) {
            this.toggleStationSelection(station)
        },
        // 复选框变化事件
        handleCheckboxChange(station, checked) {
            this.toggleStationSelection(station)
        },
        // 切换电站选择状态
        toggleStationSelection(station){
            const index = this.selectTableStation.indexOf(station.id)
            if(index > -1){
                this.selectTableStation.splice(index, 1)
            }else{
                this.selectTableStation.push(station.id)
            }
        },
        // 检查电站是否被选择
        isStationSelected(station){
            return this.selectTableStation.includes(station.id)
        },
        // 清空选择
        clearSelection(){
            this.selectTableStation = []
        }
    }
}
</script>

<style scoped lang="scss">
.content{
    display: grid;
    grid-template-columns: 430px 1fr;
    height: calc(100vh - 180px);
    margin-top: 10px;
    
    .left-wrapper{
        width:430px;
        height: calc(100vh - 180px);
        overflow: auto;
        border-right: 1px solid #e6e6e6;
    }
    
    .right-wrapper{
        margin-left: 10px;
        height: calc(100vh - 180px);
        display: flex;
        flex-direction: column;
        padding:0 20px;
    }
}

.station-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #e6e6e6;
    margin-bottom: 15px;
    
    .header-left {
        display: flex;
        align-items: center;
    }
}

.station-content {
    flex: 1;
    overflow: auto;
    padding: 10px 0;
}

.loading-container {
    padding: 20px;
}

.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #909399;
    
    p {
        margin-top: 10px;
        font-size: 14px;
    }
}

.station-cards {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 16px;
    padding: 10px;
}

.station-card {
    border: 1px solid #e6e6e6;
    border-radius: 8px;
    background: white;
    transition: all 0.3s ease;
    position: relative;
    min-height: 200px;
    display: flex;
    flex-direction: column;
    
    &:hover {
        border-color: #409eff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    &.selected {
        border-color: #409eff;
        background: #f0f7ff;
    }
}

.card-main {
    flex: 1;
    padding: 16px;
    cursor: pointer;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
    
    .station-name {
        font-weight: 600;
        color: #303133;
        display: flex;
        align-items: center;
        flex: 1;
        
        i {
            margin-right: 6px;
            color: #409eff;
        }
    }
}

.card-content {
    .info-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 6px;
        font-size: 13px;
        
        .label {
            color: #606266;
            flex-shrink: 0;
        }
        
        .value {
            color: #303133;
            text-align: right;
            flex: 1;
            margin-left: 8px;
            word-break: break-all;
        }
    }
}

.card-controls {
    border-top: 1px solid #f0f0f0;
    padding: 12px 16px;
    background: rgba(250, 250, 250, 0.8);
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 50px;
    
    .station-checkbox {
        margin: 0;
        
        ::v-deep .el-checkbox__label {
            font-size: 13px;
            color: #606266;
        }
    }
    
    .selected-badge {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #67c23a;
        background: rgba(103, 194, 58, 0.1);
        padding: 4px 8px;
        border-radius: 4px;
        
        .selected-icon {
            margin-right: 4px;
        }
        
        .selected-text {
            font-size: 12px;
            font-weight: 500;
        }
    }
}

.selection-info {
    padding: 12px;
    border-top: 1px solid #e6e6e6;
    background: #fafafa;
    display: flex;
    align-items: center;
    justify-content: center;
}

.custom-tabs {
    ::v-deep .el-tabs__header {
        margin-bottom: 0;
    }
    
    ::v-deep .el-tabs__item {
        font-weight: 500;
    }
}

.btnGroup {
    text-align: right;
    margin-top: 20px;
}

// 确保复选框可点击
::v-deep .station-checkbox {
    .el-checkbox {
        display: flex;
        align-items: center;
    }
    
    .el-checkbox__input {
        position: relative;
        z-index: 10;
    }
    
    .el-checkbox__inner {
        z-index: 11;
    }
}

.checkbox-label {
    margin-left: 4px;
    font-size: 13px;
    color: #606266;
}
</style>